import store from '@/store'
import tools from '@/utils/tools'
let input
// 创建input type:file
export default (needPercent, inputAccept, needFile) => {
  return new Promise((resolve, reject) => {
    input = document.createElement('input')
    input.type = 'file'
    input.multiple = true
    if (inputAccept) {
      input.accept = inputAccept
    }
    input.style.display = 'none'
    document.body.appendChild(input)
    input.click()
    input.onchange = (e) => {
      const files = e.target.files
      const forms = new FormData()
      files.forEach(item => {
        item = new File([item], encodeURI(item.name), {
          type: item.type
        })
        forms.append('file', item)
      })
      if (needPercent) {
        store.commit('filePage/set_ifShowDialog', true, { root: true })
      }
      store.dispatch('file/uploadFile', { file: forms, needPercent }).then(res => {
        if (needFile) {
          const newFiles = [...files].map(item => tools.dataDealer.blobToUrl(item))
          resolve({ files: newFiles, data: res.data })
          return
        }
        resolve(res)
      }).catch(err => {
        reject(err)
      })
      removeInput()
    }
  })
}

// 移除input
const removeInput = () => {
  document.body.removeChild(input)
}
